import 'package:flutter/material.dart';
import 'dart:io';
import 'package:flutter/gestures.dart';
import 'package:get/get.dart';
import '../controller/auth_controller.dart';
import '../controller/setting_controller.dart';
import 'web_view_page.dart';

class LoginDialog extends StatefulWidget {
  @override
  _LoginDialogState createState() => _LoginDialogState();
}

class _LoginDialogState extends State<LoginDialog> {
  final AuthController authController = Get.find();
  bool _isAgreed = false;

  @override
  void initState() {
    super.initState();
    // 监听登录状态变化（只触发一次），成功后确保关闭弹窗并返回 true
    once(authController.isBindAccount, (bool isBindAccount) {
      if (isBindAccount == true && mounted) {
        if (Get.isDialogOpen == true) {
          Get.back(result: true);
        } else if (Navigator.of(context).canPop()) {
          Navigator.of(context).pop(true);
        }
      }
    });
  }

  void _handleLogin() async {
    if (!_isAgreed) {
      Get.snackbar(
        'hint'.tr,
        'privacy_policy_agreement'.tr,
        backgroundColor: Color(0xFF2A2A2A),
        colorText: Colors.white,
        snackPosition: SnackPosition.BOTTOM,
        margin: EdgeInsets.all(16),
      );
      return;
    }

    // 根据平台执行登录
    final success = await authController.signInWithPlatform();
    // 二次确认弹窗是否关闭，没有关闭则关闭并返回 true
    if (success && mounted) {
      if (Get.isDialogOpen == true) {
        Get.back(result: true);
      } else if (Navigator.of(context).canPop()) {
        Navigator.of(context).pop(true);
      }
    }
  }

  void _openPrivacyPolicy() {
    // 尝试获取 SettingController 实例
    SettingController? settingController;
    try {
      settingController = Get.find<SettingController>();
    } catch (e) {
      // 如果找不到实例，settingController 将保持为 null
    }
    
    // 检查 settingController 是否为空，如果为空或 URL 为空则使用默认值
    final privacyUrl = settingController != null && settingController.privacyPolicyUrl.value.isNotEmpty
        ? settingController.privacyPolicyUrl.value
        : 'https://bit-fury.com'; // 默认隐私政策URL
    
    Get.to(() => WebViewPage(
      url: privacyUrl,
      title: 'privacy_policy'.tr,
    ));
  }

  void _openUserAgreement() {
    Get.to(() => WebViewPage(
      url: 'https://bit-fury.com', // 替换为实际的用户协议URL
      title: 'user_agreement'.tr,
    ));
  }

  @override
  Widget build(BuildContext context) {
    return Dialog(
      backgroundColor: Colors.transparent,
      elevation: 0,
      insetPadding: EdgeInsets.symmetric(horizontal: 20),
      child: Container(
        decoration: BoxDecoration(
          color: Color(0xFF1A1A1A),
          borderRadius: BorderRadius.circular(30),
        ),
        padding: EdgeInsets.fromLTRB(24, 32, 24, 32),
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            Text(
              'Login to Continue',
              style: TextStyle(
                color: Colors.white,
                fontSize: 32,
                fontWeight: FontWeight.w600,
              ),
              textAlign: TextAlign.center,
            ),
            SizedBox(height: 16),
            Text(
              'Login to purchase contracts\nand manage assets',
              textAlign: TextAlign.center,
              style: TextStyle(
                color: Colors.white.withOpacity(0.7),
                fontSize: 18,
                height: 1.4,
              ),
            ),
            SizedBox(height: 40),
            Row(
              crossAxisAlignment: CrossAxisAlignment.center,
              children: [
                SizedBox(
                  width: 24,
                  height: 24,
                  child: Checkbox(
                    value: _isAgreed,
                    onChanged: (value) {
                      setState(() {
                        _isAgreed = value ?? false;
                      });
                    },
                    fillColor: MaterialStateProperty.resolveWith<Color>(
                      (Set<MaterialState> states) {
                        if (states.contains(MaterialState.selected)) {
                          return Colors.transparent;
                        }
                        return Colors.transparent;
                      },
                    ),
                    side: BorderSide(color: Colors.grey[400]!, width: 1.5),
                    shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(4),
                    ),
                    checkColor: Colors.white,
                  ),
                ),
                SizedBox(width: 8),
                Expanded(
                  child: RichText(
                    text: TextSpan(
                      style: TextStyle(color: Colors.white.withOpacity(0.7), fontSize: 14),
                      children: [
                        TextSpan(text: 'I have read and agree to the '),
                        TextSpan(
                          text: 'Privacy Policy',
                          style: TextStyle(
                            color: Colors.amber,
                            fontSize: 14,
                            decoration: TextDecoration.underline,
                          ),
                          recognizer: TapGestureRecognizer()
                            ..onTap = _openPrivacyPolicy,
                        ),
                      ],
                    ),
                  ),
                ),
              ],
            ),
            SizedBox(height: 40),
            Obx(() => Container(
                  width: double.infinity,
                  height: 56,
                  child: ElevatedButton(
                    onPressed: authController.isLoading.value
                        ? null
                        : _handleLogin,
                    style: ElevatedButton.styleFrom(
                      shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.circular(28), // 按钮高度的一半 (56/2=28)
                      ),
                      padding: EdgeInsets.zero,
                      backgroundColor: Colors.transparent,
                      elevation: 0,
                    ),
                    child: Ink(
                      decoration: BoxDecoration(
                        borderRadius: BorderRadius.circular(28),
                        gradient: _isAgreed
                            ? LinearGradient(
                                colors: [Color(0xFFFFF0B0), Color(0xFFF0D080)],
                                begin: Alignment.topLeft,
                                end: Alignment.bottomRight,
                              )
                            : null,
                        color: _isAgreed ? null : Color(0xFF4A4A4A),
                      ),
                      child: Container(
                        alignment: Alignment.center,
                        child: authController.isLoading.value
                            ? SizedBox(
                                width: 24,
                                height: 24,
                                child: CircularProgressIndicator(
                                  strokeWidth: 2.5,
                                  valueColor:
                                      AlwaysStoppedAnimation<Color>(Colors.white),
                                ),
                              )
                            : Row(
                              mainAxisAlignment: MainAxisAlignment.center,
                              children: [
                                Platform.isIOS 
                                ? Image(
                                    image: AssetImage("assets/bit_fury_login_apple_icon.png"),
                                    width: 24,
                                    height: 24,
                                  )
                                : Image(
                                    image: AssetImage("assets/bit_fury_login_google_icon.png"),
                                    width: 24,
                                    height: 24,
                                  ),
                                SizedBox(width: 12),
                                Text(
                                  Platform.isIOS 
                                  ? 'Sign in with Apple' 
                                  : 'Sign in with Google',
                                  style: TextStyle(
                                    color: Colors.black,
                                    fontSize: 16,
                                    fontWeight: FontWeight.w500,
                                  ),
                                ),
                              ],
                            ),
                    ),
                  ),
                ))),
          ],
        ),
      ),
    );
  }
}